#include "sys_uart.h"
#include "sys_clock.h"
#include "sys_dram.h"
#include "sys_gpio.h"
#include "sys_delay.h"
#include <string.h>
#include <stdio.h>
#include "sys_spi.h"

#ifdef EVB_IO
#define DEBUG_UART_PORT UART0
#else
#define DEBUG_UART_PORT UART2
#endif

/*---------------------------------------------------
---- main
---- main
----------------------------------------------------*/
int main(void)
{ 
	char BOOTEXE[8]="eGON.BT1";	
	void	(*fw_func)(void);	
	unsigned int executeAddr=0x80000000;//RAM 程序执行地址
	unsigned int spireadAddr=0x6000;//FLASH 24k位置 BOOT1 地址

	int i;

	char file_h[32];
	unsigned int file_size=0;
	
	unsigned int CPU_Frequency_hz=408*1000000;//HZ
	
	int dram_size;

#ifdef EVB_IO
	// PA0
	//GPIO_Congif(GPIOA, 0, GPIO_Mode_IN, GPIO_PuPd_UP);
	//if (0 == GPIO_READ(GPIOA, 0)) {
		//((void(*)())0xFFFF0000)();
//		((void(*)())0xFFFF4160)();
	//}
#else
	// PA1 PE2
	GPIO_Congif(GPIOA, 1, GPIO_Mode_OUT, GPIO_PuPd_UP);
	GPIO_Congif(GPIOE, 2, GPIO_Mode_OUT, GPIO_PuPd_UP);

	GPIO_RESET(GPIOA, 1);
	GPIO_SET(GPIOE, 2);
#endif

	dram_size = sys_dram_init();//初始化必须在时钟初始化以前，延时原因	

	sys_clock_init(CPU_Frequency_hz);
	//((void(*)())0xFFFF0000)();

	Sys_Uart_Init(DEBUG_UART_PORT, CPU_Frequency_hz, 115200, 0);
	Sys_SET_UART_DBG(DEBUG_UART_PORT);	

	sysprintf("\r\n\r\n*****************************************\r\n");	
	sysprintf("F1C%d00S BOOT0 START...\r\n",dram_size/32);
	sysprintf("XiaoTaoQiKJ [2020-05-29]...\r\n");
	sysprintf("QQ:718595426\r\n\r\n");		
	sysprintf("CPU Frequency:%d Hz\r\n",CPU_Frequency_hz);		
	sysprintf("DRAM Size: %d MB\r\n",dram_size);
	sysprintf("*****************************************\r\n");	

#if 0
	for (;;) {
		GPIO_RESET(GPIOE, 2);
		delay_ms(500);
		GPIO_SET(GPIOE, 2);
		delay_ms(500);
	}
#endif

#ifdef EVB_IO
//	if (0 == GPIO_READ(GPIOA, 0)) {
//		sysprintf("User key pressed.\r\n");
//		((void(*)())0xFFFF4160)();
//	}
#endif

	spi_flash_init(SPI0);
	//读文件头
	sys_spi_flash_read(SPI0,spireadAddr,file_h,32);

	for(i=0;i<8;i++)if(file_h[4+i]!=BOOTEXE[i])break;
	if(i==8)//可执行文件
	{
		sysprintf("\r\nRead BOOT1...\r\n");
		//读文件大小
		file_size=file_h[0x13]<<24 | file_h[0x12]<<16 | file_h[0x11]<<8 | file_h[0x10]; 
		file_size=file_size-32;
		sysprintf("BOOT1 at Flash 0x%08x\r\n",spireadAddr);
		sysprintf("File Size %d \r\n",file_size);
		//读文件
		sysprintf("Read BOOT1 to RAM 0x%08x \r\n",executeAddr);
		sys_spi_flash_read(SPI0,spireadAddr+32,(unsigned int *)(executeAddr),file_size);
		//执行
		sysprintf("Jump BOOT1...\r\n");
		fw_func = (void(*)(void))(executeAddr);
		fw_func();	
	}	
	
  sysprintf("BOOT0 OUT...\r\n");	
  while(1)
  { 

  }
}
